<template>
  <div class="charts-container">
    <div>
      <canvas id="charts-body" width="500" height="500"></canvas>
    </div>
  </div>
</template>

<script>
import {defineComponent, reactive} from "vue";

export default defineComponent({
  components: {},
  props: {},
  setup(props, context) {

    return {
      canvsEle: reactive({}),
      canvsContext: reactive({}),
      regMap: reactive({
        rect:
            [
              {type: 'fill', style: '#123', pos: [0, 0], size: [200, 100]},
              {type: 'stroke', style: '#123', pos: [50, 50], size: [200, 100]},
            ]

      })
    }
  },
  mounted() {
    this.canvsEle = document.getElementById("charts-body");
    this.canvsContext = this.canvsEle.getContext("2d");
    this.canvsContext.fillStyle = "#ea1"
    this.canvsContext.fillRect(0, 0, 500, 500)
    this.canvsContext.strokeRect(10, 10, 50, 50)
    this.redraw();
    let temp = 0
    const movehandler = e => {

        this.regMap.rect[0].pos[0]+=e.clientY - temp
        this.regMap.rect[1].pos[0]+=e.clientY - temp

      temp = e.clientY
    }
    const downHandler = e => {
      temp = e.clientY
      this.canvsEle.removeEventListener('mousemove', movehandler)
      this.canvsEle.addEventListener('mousemove', movehandler)
      document.body.addEventListener('mouseup', upHandler)
    }
    const upHandler = e => {
      this.canvsEle.removeEventListener('mousemove', movehandler)
    }
    this.canvsEle.addEventListener('mousedown', downHandler)

    const mouseenterHandler = e=>{
      this.regMap.rect[0].style = '#f0f'
      this.regMap.rect[1].style = '#0ff'
    }
    const mouseleaveHandler = e=>{
      this.regMap.rect[0].style = '#123'
      this.regMap.rect[1].style = '#123'
    }
    this.canvsEle.addEventListener('mouseenter', mouseenterHandler)
    this.canvsEle.addEventListener('mouseleave', mouseleaveHandler)
  },
  methods: {
    redraw() {
      this.canvsContext.clearRect(0, 0, 500, 500)
      // rect
      let rects = this.regMap.rect
      rects.forEach(rect => {
        if (rect.type === 'fill') {
          this.canvsContext.save()
          this.canvsContext.fillStyle = rect.style
          this.canvsContext.fillRect(rect.pos[0], rect.pos[1], rect.size[0], rect.size[1])
          this.canvsContext.restore()
        } else {
          this.canvsContext.save()
          this.canvsContext.strokeStyle = rect.style
          this.canvsContext.strokeRect(rect.pos[0], rect.pos[1], rect.size[0], rect.size[1])
          this.canvsContext.restore()
        }
      })
      requestAnimationFrame(this.redraw);
    }
  }
})
</script>

<style scoped>
#charts-body {
  border: 1px solid red;
}
</style>
